package gogo

import (
	"crypto/subtle"
	"net/http"
)

// BasicAuthFunc 是用于验证用户名和密码的函数类型
type BasicAuthFunc func(username, password string) bool

// BasicAuth 中间件用于处理HTTP Basic Authentication
func BasicAuth(authFunc BasicAuthFunc, realm string) func(*HTTPContext) bool {
	return func(ctx *HTTPContext) bool {
		username, passwd := ctx.GetBasicAuthUserNameAndPasswd()

		if username != "" && passwd != "" {
			// 验证用户名和密码
			if authFunc(username, passwd) {
				return true
			}
		}

		ctx.w.Header().Set("WWW-Authenticate", `Basic realm="`+realm+`"`)
		ctx.w.WriteHeader(http.StatusUnauthorized)
		ctx.WriteString("Unauthorized\n")
		return false
	}
}

// SecureCompare 安全地比较两个字符串，防止时序攻击
func SecureCompare(given, actual string) bool {
	return subtle.ConstantTimeCompare([]byte(given), []byte(actual)) == 1
}
